/**
 * Copyright 2014 
 * Author：liwen
 * 创建日期：2014-11-22
 */
package com.acoreful.menos.web.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.acoreful.menos.web.view.StringView;

public class HandlerExceptionResolver extends SimpleMappingExceptionResolver{
	Logger log =  LoggerFactory.getLogger(getClass());
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		HandlerMethod handlerMethod;
		if (handler instanceof HandlerMethod) {
             handlerMethod = (HandlerMethod)handler;
        } else {
            this.setResponseNoCache(response);
            return super.resolveException(request, response, handler, ex);
        }
		ex.printStackTrace();
        log.error(ex.getMessage());
		if(handlerMethod.getMethodAnnotation(ResponseBody.class)!=null){
			ModelAndView modelAndView = new ModelAndView();
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("status", false);
			map.put("message", "系统繁忙，请稍后重试");
			map.put("noPri", "N");
			modelAndView.addObject("exceptionInfo",null/*JSONObject.fromObject(map).toString()*/);
			modelAndView.setView(new StringView("exceptionInfo"));
			return modelAndView;
		}
		log.error(ex.getMessage());
		this.setResponseNoCache(response);
		Exception e = new Exception("系统忙，请稍后重试",ex.getCause());
		return super.resolveException(request, response, handler, e);
	}
	private void setResponseNoCache(HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-cache,no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("expires", -1);
	}
}
